package cn.quantgroup.rabbitmq.pubsub;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

/**
 * Created by 11 on 2016/12/15.
 */
public class EmitLog {
    private static final String EXCHANGE_NAME = "logs";
    private static final String EXCHANGE_TYPE = "fanout";

    public static void main(String[] args) throws Exception{
        //创建连接工厂,设置连接地址，用户名，密码
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        factory.setUsername("admin");
        factory.setPassword("admin");
        //创建连接
        Connection connection = factory.newConnection();
        //通过连接创建信道,信道的创建和销毁代价比连接要小的多
        Channel channel = connection.createChannel();
        //声明交换机
        channel.exchangeDeclare(EXCHANGE_NAME, EXCHANGE_TYPE);
        //发送的消息体
        String message = getMessage(args);
        //发送消息,消息体格式为字节数组,fanout类型交换机发送消息无需指定routing key
        channel.basicPublish(EXCHANGE_NAME, "", null, message.getBytes());
        System.out.println(" [x] Sent '" + message + "'");
        //关闭连接和通道
        channel.close();
        connection.close();
    }

    /**
     * 解析命令行参数
     * @param args
     * @return
     */
    public static String getMessage(String[] args){
        if(args.length < 1){
            return "Hello, World!";
        }
        return joinStrings(args, " ");
    }

    /**
     * 使用指定分隔符对数组分割
     * @param args
     * @param delimiter
     * @return 拼接后的字符串
     */
    public static String joinStrings(String[] args, String delimiter){
        int length = args.length;
        if(length == 0){
            return "";
        }
        StringBuilder word = new StringBuilder(args[0]);
        for(int i = 1; i < length; i ++){
            word.append(delimiter).append(args[i]);
        }
        return word.toString();
    }
}